package com.lagou.server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * MiniCat的主类
 * 1）提供服务、接收请求（Socket通信）
 * 2）请求信息封装成Request对象（Response对象）
 * 3）客户端请求资源：资源分成静态资源（html）和动态资源（Servlet）
 * 4）资源返回给客户端浏览器
 */
public class Bootstrap {

    // 定义socket监听的端口号
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Map<String, HttpServlet> servletMap = new HashMap<>();

    /**
     * 使用线程池
     *
     * @throws Exception
     */
    public void start() throws Exception {
        // 首先加载解析相关的配置
        loadServlet();
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("===========> MiniCat start on port: " + port + " <===========");

        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        // 定义一个线程池
        ExecutorService executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            executorService.execute(requestProcessor);
        }
    }


    /**
     * 加载解析web.xml，初始化servlet
     */
    private void loadServlet() {
        String appBase = "/Users/webapps";
        File baseDirector = new File(appBase);
        if(baseDirector.isDirectory()){
            // 遍历这个文件夹
            for (File file : Objects.requireNonNull(baseDirector.listFiles())) {
                if(file.isDirectory()){
                    // 进到具体的目录下
                    try{
                        // context路径
                        String contextPath = "/" + file.getName();

                        // 然后读取web.xml文件
                        // 并且根据web.xml的文件配置，加载servlet
                        String webXmlPath = file.getPath() + "/WEB-INF/web.xml";
                        String classesPath = file.getPath() + "/WEB-INF/classes/";
                        FileInputStream fileInputStream = new FileInputStream(new File(webXmlPath));
                        SAXReader saxReader = new SAXReader();
                        Document document = saxReader.read(fileInputStream);
                        Element rootElement = document.getRootElement();

                        List<Element> selectNodes = rootElement.selectNodes("//servlet");

                        for (int i = 0; i < selectNodes.size(); i++) {
                            Element element = selectNodes.get(i);

                            Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                            String servletName = servletNameElement.getStringValue();

                            Element servletClassElement = (Element) element.selectSingleNode("servlet-class");

                            // 配置的值是这样: com.lagou.server.LagouServlet
                            // 需要转化为路径: com/lagou/server/LagouServlet
                            String servletPath = servletClassElement.getStringValue().replace('.', '/');

                            // 根据servlet-name的值找到url-pattern
                            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                            // 使用自定义的类加载器加载servlet
                            MyClassLoader myClassLoader = new MyClassLoader();
                            Class<?> clazz = myClassLoader.findClass(classesPath + servletPath);

                            // 最后放到servletMap中要加上contextPath
                            servletMap.put(contextPath + urlPattern, (HttpServlet) clazz.newInstance());
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    /**
     * MiniCat的启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
